/**
 * Window containing the module tree to add a module container
 *
 * @class dfly.windowAddContainer
 * @extends YAHOO.widget.Panel
 * @constructor
 */
dfly.windowAddContainer = function() {
   
   // Call the parent class constructor
   dfly.windowAddContainer.superclass.constructor.call(this, "addContainer", { close:true, visible:false, modal:true, width: 200, effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.25} });
   
   // Render the treeView
   this.renderContent();
   
   // Render the window into document.body
   this.render(document.body);
};


YAHOO.extend(dfly.windowAddContainer, YAHOO.widget.Panel, {
   
   getDirNode: function(path) {
      var directoryKey = path.join('/');
      if(this.directories[directoryKey]) {
         return this.directories[directoryKey];
      }
      else {
         if( path.length == 0) {
            return this.tree.getRoot();
         }
         var parentNode = this.getDirNode( path.slice(0,path.length-1) );
         var node = new YAHOO.widget.TextNode(path[path.length-1], parentNode, false);    
         this.directories[directoryKey] = node;
         return node;
      }
   },
   
   /**
    * Refresh the treepanel with the true database modules
    */
   buildWithModules: function() {
      
      // Keep track of the TreeNodes for folders
      if(!this.directories){  this.directories = {}; }
      
      // Select all the modules and add them
      var paths = dfly.ModuleModel.getAllModules();
      
      for(var k = 0 ; k < paths.length ; k++) {
         var path = paths[k].split('/');
         var moduleName = path[path.length-1];
         var dirNode = this.getDirNode( path.slice(1,path.length-1) );
            
         var alreadyPresent = false;
         for(var i = 0; i < dirNode.children.length; i++) {
            if(dirNode.children[i].data == moduleName) {
               alreadyPresent = true;
               i=dirNode.children.length;
            }
         }
            
         if(!alreadyPresent) {
            new YAHOO.widget.TextNode( moduleName, dirNode, false);    
         }
      }
      
   },
   
   /**
    * Refresh the tree
    */
   refreshModuleList: function() {
      this.buildWithModules();
      this.tree.getRoot().refresh();
   },
   
   removeModuleFromTree: function(moduleToDelete) {
      
      var path = moduleToDelete.split('/');
      var moduleName = path[path.length-1];
      var dirNode = this.getDirNode( path.slice(1,path.length-1) );
         
      for(var i = 0; i < dirNode.children.length; i++) {
         if(dirNode.children[i].data == moduleName) {
            this.tree.removeNode(dirNode.children[i]);
            
            /*dirNode.refresh();
            var directoryKey = path.join('/');
            this.directories[directoryKey]*/
            // TODO: recursively delete empty folders
            
            return;
         }
      }
      
   },
   
   /**
    * Override buildMask to install a click listener on the mask that closes the dialog
    */
   buildMask: function() {
      dfly.windowAddContainer.superclass.buildMask.call(this);
      // buildMask is called on each show, so we use the maskListener property to add the listener only once
      if(!this.maskListener) {
         this.maskListener = true;  
         YAHOO.util.Event.addListener('addContainer_mask', 'click', this.hide, this, true);
      }
   },
   
   /**
    * Render the content of the window
    */
   renderContent: function() {
      
      // set the title 
      this.setHeader("Select a module");

      // Create a div wrapper for the TreeView
      this.browseBox = WireIt.cn('div');      
      this.tree = new YAHOO.widget.TreeView(this.browseBox);
      
      // Build the tree from dfly.modules
      this.buildWithModules();

      // Draw (render) the tree
      this.tree.draw();
      
      // Install a listener for label clicks 
      this.tree.subscribe("labelClick", this.onLabelClick, this, true);
      
      // Set the div wrapper as the window body
      this.setBody(this.browseBox);
   },
   
   /**
    * Called when the user clicked on a label in the module tree
    */
   onLabelClick: function(node) {
      
      // If the node has some child nodes, it is a category => quit
      if(node.children.length != 0) { return; }
      
      // Hide the window
      this.hide();
      
      
      this.lastCallback.call(this.lastScope, this.getModuleNameFromNode(node) );
   },
   
   /**
    * Get the module name from the clicked node
    */
   getModuleNameFromNode: function(node) {
      var moduleName = "";
      var parent = node.parent;
      var path = [ node.getLabelEl().innerHTML ];
      var root = this.tree.getRoot();
      while( parent != root) {
         path.push(parent.getLabelEl().innerHTML);
         parent = parent.parent;
      }
      for(var i = path.length-1 ; i >= 0 ; i--) {
         moduleName += "/"+path[i];
      }
      return moduleName;
   },
   
   /**
    * Override show to set the position and stores it into lastPosition
    */
   show: function(callback, scope, position) {
      
      dfly.windowAddContainer.superclass.show.call(this);
      
      this.lastCallback = callback;
      this.lastScope = scope;
      
      if(position) {
         // Save position for later
         this.lastPosition = position;
         // Move the window to the new position
         this.moveTo(position[0]-100, Math.max(position[1]-50, 0) );
      }
      else {
         this.center();
      }
   }
   
});

